

function calculateEMA(prices, period) {
    let k = 2 / (period + 1)
    let priceLength = prices.length
    let ema = [];
    ema[0] = prices.reduce((a, b) => a + b, 0) / priceLength // 初始EMA为简单移动平均  

    for (let i = 1; i < priceLength; i++) {
        ema[i] = ((prices[i] - ema[i - 1]) * k) + ema[i - 1]
    }

    return ema
}

function calculateMACD({ data = [], shortPeriod = 12, longPeriod = 26, signalPeriod = 9 }) {
    let result = {}
    let prices = data.map(item => item.close)
    let shortEMA = calculateEMA(prices, shortPeriod)
    let longEMA = calculateEMA(prices, longPeriod)
    let diff = []

    let shortEMALength = shortEMA.length
    let longEMALength = longEMA.length

    for (let i = 0; i < shortEMALength && i < longEMALength; i++) {
        diff[i] = Number((shortEMA[i] - longEMA[i]).toFixed(2))
    }

    let dea = calculateEMA(diff, signalPeriod)
    let diffLength = diff.length
    let deaLength = dea.length

    // 计算每个MACD柱的高度（即MACD值与信号线值的差）  
    let macd = [];
    for (let i = 0; i < diffLength && i < deaLength; i++) {
        macd[i] = Number((diff[i] - dea[i]).toFixed(2)) // 注意：这实际上是MACD柱的“差异”，不是传统意义上的“高度”（因为信号线是基于MACD计算的）  
        // 如果要计算传统意义上的MACD柱高度，应该直接使用macd[i]（不考虑信号线）  
    }

    result = { macd, diff, dea }

    return result
}

module.exports = calculateMACD